<?php


namespace app\admin\controller;

use app\admin\BaseController;
use app\admin\common\Selector;
use app\admin\CommonException;
use app\admin\model\GroupRole;
use app\admin\model\Role as RoleModel;

class Role extends BaseController
{
    public function index()
    {
        $model = new RoleModel();
        $list = $model->getRoles($this->request);
        $select = [
            'id' => '角色编号',
            'role_name' => '角色名称'
        ];
        $selector = Selector::render($select, 'search', $this->request->get('search', ''));
        return view('role/index', [
            'list' => $list->toArray()['data'] ?? [],
            'page' => $list->__toString(),
            'selector' => $selector
        ]);
    }

    /**
     * @return bool|\think\response\View
     * @throws CommonException
     */
    public function add()
    {
        $data = $this->request->post();
        if (!$data) {
            return view('/role/add', ['url' => '/role/add']);
        }

        $validate = new \app\validate\role();

        $result = $validate->check($data);
        if (!$result) error($validate->getError(), '', 10086);

        //新增
        $model = new RoleModel();
        $model->data($data, true);
        $res = $model->save();
        if ($res) {
            $this->success('添加成功!', '/role/add');
        }
        error('添加失败!请稍候再试');
        return false;
    }

    /**
     * 删除
     * @throws
     */
    public function del()
    {
        $model = new RoleModel();
        $id = $this->request->get('id', '');
        if (!$id) return false;
        $role = $model->find($id);
        if (!$role) return false;
        return $role->delete();
    }

    /**
     * 检查角色名唯一
     */
    public function checkName()
    {
        $name = $this->request->post('role_name');
        $id = $this->request->post('id', 0);
        $validate = new \app\validate\role();
        $data = ['role_name' => $name];
        if ($id) $data['id'] = $id;
        $result = $validate->check($data);
        return $result;
    }

    /**
     * @return \think\response\View
     * @throws
     */
    public function update()
    {
        $data = $this->request->post();
        if (!$data) {
            $id = $this->request->request('id', '');
            if (!$id) throw new CommonException('缺少参数!', '/role/index');
            $role = RoleModel::find($id);
            if (!$role) throw new CommonException('请刷新后重试!', '/role/index');
            return view('role/add', ['data' => $role, 'url' => '/role/update']);
        }

        //修改
        $role = RoleModel::find($data['id']);
        if (!$role) throw new CommonException('请刷新后重试!', '/role/index');

        $validate = new \app\validate\role();
        $result = $validate->check($data);
        if (!$result) error($validate->getError(), '', 10086);

        //修改
        $role->data($data, true);
        $res = $role->save();
        if ($res) {
            $this->success('修改成功!', '/role/update.html?id='.$data['id']);
        }
        error('修改失败!请稍候再试');
    }

    /**
     * 角色选择权限组
     * @return bool|\think\response\View
     * @throws CommonException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function addGroup(){
        //ajax
        if($this->request->isAjax()){
            $type = $this->request->get('type');
            $roleId = $this->request->get('id');
            $groupId = $this->request->get('group_id');
            //添加组
            if($type == 'add'){
                $bool = GroupRole::where('role_id',$roleId)->where('group_id',$groupId)->find();
                if(!$bool){
                    if( (new GroupRole())->data(['role_id'=>$roleId,'group_id'=>$groupId])->save() ){
                        return true;
                    }
                }
            }
            //删除组
            if($type == 'del'){
                $bool = GroupRole::where('role_id',$roleId)->where('group_id',$groupId)->find();
                if($bool){
                    if( GroupRole::where(['role_id'=>$roleId,'group_id'=>$groupId])->delete() ){
                        return true;
                    }
                }
            }
            return false;
        }


        //html
        $roleId = $this->request->get('id');
        if (!$roleId) throw new CommonException('缺少参数!', '/role/index');
        $role = RoleModel::find($roleId);
        if (!$role) throw new CommonException('请刷新后重试!', '/role/index');

        //全部的权限组
        $groups = \app\admin\model\RoleGroup::select()->toArray();
        $selectGroups = GroupRole::where('role_id',$roleId)->column('group_id');
        foreach ($groups as &$val){
            $val['checked'] = false;
            if($selectGroups){
                if(in_array($val['id'],$selectGroups))  $val['checked'] = true;
            }
        }
        $data = [
            'data'=>$role,
            'groups'=>$groups
        ];
        return view('role/addgroup',$data);
    }

}